package com.gitee.andy.zpush.kernel;

import java.util.Objects;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

public abstract class Session {
	protected Channel channel;
	
	protected Integer id;

	private static final AttributeKey<Session> sessionKey = AttributeKey.valueOf(Session.class.getName());

	protected Integer id() {
		return id;
	}

	public Session bind(ChannelHandlerContext ctx) {
		return bind(ctx.channel());
	}

	public Session bind(Channel channel) {
		Objects.requireNonNull(channel, "channel is null");
		channel.attr(sessionKey).set(this);
		this.channel = channel;
		this.id = channel.remoteAddress().hashCode();
		return this;
	}

	public void write(Object msg) {
		if(channel == null || !channel.isActive())return;
		this.channel.writeAndFlush(msg);
	}

	public static Session get(ChannelHandlerContext ctx) {
		return get(ctx.channel());
	}

	public static Session get(Channel channel) {
		Objects.requireNonNull(channel, "channel is null");
		return channel.attr(sessionKey).get();
	}

	public static Session unbind(ChannelHandlerContext ctx) {
		return unbind(ctx.channel());
	}

	public static Session unbind(Channel channel) {
		Session session = get(channel);
		if(session == null){
			return null;
		}
		channel.attr(sessionKey).set(null);
		session.channel = null;
		return session;
	}
}
